<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label=" 编码" prop="number">
        <el-input
          v-model="queryParams.number"
          placeholder="请输入 编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

<!--      <el-form-item label=" 发货方" prop="sendoutCompany">-->
<!--        <el-input-->
<!--          v-model="queryParams.sendoutCompany"-->
<!--          placeholder="请输入 发货方"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->

      <el-form-item label=" 客户" prop="receiveCompany">
        <el-input
          v-model="queryParams.receiveCompany"
          placeholder="请输入 客户"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


<!--      <el-form-item label=" 开始时间" prop="signdate">-->
<!--        <el-date-picker clearable-->
<!--          v-model="queryParams.signdate"-->
<!--          type="date"-->
<!--          value-format="yyyy-MM-dd"-->
<!--          placeholder="请选择 开始时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->

      <el-form-item label=" 货物名称" prop="itemName">
        <el-input
          v-model="queryParams.itemName"
          placeholder="请输入 货物名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>

    </el-form>

    <el-row :gutter="10" class="mb8">

        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:salePlan:add']"
        >新增</el-button>

        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:salePlan:edit']"
        >修改</el-button>

        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:salePlan:remove']"
        >删除</el-button>

        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:salePlan:export']"
        >导出</el-button>
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleSpecExport"-->
<!--        >自定义导出</el-button>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="salePlanList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="60" align="center" />
      <el-table-column label="id" align="center" prop="id" v-if="false"/>
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label=" 编码" align="center" prop="number" :show-overflow-tooltip="true" width="130"/>
      <el-table-column label="提货码" align="center" prop="pickCode" />
<!--      <el-table-column label=" 发货方" align="center" prop="sendoutCompany"  :show-overflow-tooltip="true" width="130"/>-->
      <el-table-column label=" 客户" align="center" prop="receiveCompany"  :show-overflow-tooltip="true" width="130"/>
      <el-table-column label=" 开始时间" align="center" prop="signdate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.signdate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label=" 结束时间" align="center" prop="enddate" />
      <el-table-column label=" 计划状态" align="center" prop="planState">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.plan_state" :value="scope.row.planState"/>
        </template>
      </el-table-column>
      <el-table-column label=" 状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.state" :value="scope.row.state"/>
        </template>
      </el-table-column>
      <el-table-column label=" 货物名称" align="center" prop="itemName" />
      <el-table-column label=" 货物价格" align="center" prop="itemPrice" />
      <el-table-column label=" 数量" align="center" prop="total" />
      <el-table-column label=" 货物规格" align="center" prop="itemModel" />
      <el-table-column label=" 完成量" align="center" prop="completed" />
      <el-table-column label=" 剩余量" align="center" prop="remain" />
      <el-table-column label=" 完成率(%)" align="center" prop="completionRate" />
      <el-table-column label=" 运单数" align="center" prop="waybillQty" />
<!--      <el-table-column label=" 计划车辆数" align="center" prop="plancarQty" />-->
<!--      <el-table-column label=" 计划完成车数" align="center" prop="planCompletedcarQty" />-->
<!--      <el-table-column label=" 计划剩余车数" align="center" prop="planRemaincarQty" />-->
      <el-table-column label=" 创建用户名" align="center" prop="createUserName" />
      <el-table-column label=" 创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:salePlan:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:salePlan:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改销售计划对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
<!--        <el-form-item label=" 发货方" prop="sendoutCompany">-->
<!--          <el-select v-model="form.sendoutCompany" placeholder="请选择发货方" clearable filterable  @change="handleSendoutChange">-->
<!--            <el-option-->
<!--              v-for="goods in this.sendOutCompanyList"-->
<!--              :key="goods.id"-->
<!--              :label="goods.name"-->
<!--              :value="goods.id"-->
<!--            />-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label=" 客户" prop="receiveCompany">
          <el-select v-model="form.receiveCompany" placeholder="请选择客户" clearable filterable  @change="handleReceiveChange">
            <el-option
              v-for="goods in this.receiveCompanyList"
              :key="goods.id"
              :label="goods.name"
              :value="goods.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label=" 开始时间" prop="signdate">
          <el-date-picker clearable
            v-model="form.signdate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择 开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label=" 结束时间" prop="enddate">
          <el-date-picker clearable
                          v-model="form.enddate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择 结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label=" 货物名称" prop="itemName">
          <el-select v-model="form.itemId" placeholder="请选择货物" clearable filterable  @change="handleGoodsChange">
            <el-option
              v-for="goods in this.goodsList"
              :key="goods.goodId"
              :label="goods.goodName"
              :value="goods.goodId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label=" 数量" prop="total">
          <el-input v-model="form.total" placeholder="请输入 数量" />
        </el-form-item>
        <el-form-item label=" 货物规格" prop="itemModel">
          <el-input v-model="form.itemModel"  :disabled="true"/>
        </el-form-item>
        <el-form-item label=" 货物价格" prop="itemPrice">
          <el-input v-model="form.itemPrice" :disabled="true" />
        </el-form-item>
<!--        <el-form-item label=" 计划车辆数" prop="plancarQty">-->
<!--          <el-input v-model="form.plancarQty" placeholder="请输入 计划车辆数" />-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSalePlan, getSalePlan, delSalePlan, addSalePlan, updateSalePlan } from "@/api/system/salePlan"
import {getGoodsPriceInfoList} from "../../../api/system/price";
import {getSendOutCompanyInfoList} from "../../../api/system/sendoutCompany.js";
import {getReceiveCompanyInfoList} from "../../../api/system/receiveCompany.js";
import axios from 'axios'

export default {
  name: "SalePlan",
  dicts: ['plan_state', 'state'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      goodsList:[],
      receiveCompanyList:[],
      sendOutCompanyList:[],
      // 销售计划表格数据
      salePlanList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //  数量时间范围
      daterangeCreateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        number: null,
        sendoutCompany: null,
        receiveCompany: null,
        signdate: null,
        itemName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        // sendoutCompany: [
        //   { required: true, message: " 发货方不能为空", trigger: "blur" }
        // ],
        receiveCompany: [
          { required: true, message: " 客户不能为空", trigger: "blur" }
        ],
        signdate: [
          { required: true, message: " 开始时间不能为空", trigger: "blur" }
        ],
        enddate: [
          { required: true, message: " 结束时间不能为空", trigger: "blur" }
        ],
        itemName: [
          { required: true, message: " 货物名称不能为空", trigger: "blur" }
        ],
        total: [
          { required: true, message: " 数量不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
    this.getGoodsList();
    this.getSendOutCompanyList();
    this.getReceiveCompanyList();
  },
  methods: {

    handleGoodsChange(goodsId) {
      if (goodsId) {
        // 根据选中的货物ID查找对应的货物信息
        const selectedGoods = this.goodsList.find(goods => goods.goodId === goodsId);
        if (selectedGoods) {
          // 设置货物规格（禁用状态）
          this.form.itemModel = selectedGoods.goodModel || '';
          // 设置货物价格
          this.form.itemPrice = selectedGoods.publicPrice || '';
          // 可以同时设置货物名称（如果需要）
          this.form.itemName = selectedGoods.goodName || '';
          this.form.itemPriceId = selectedGoods.id || '';
          this.form.itemId = selectedGoods.goodId || '';
        }
      } else {
        // 清空选择时，重置相关字段
        this.form.itemModel = '';
        this.form.itemPrice = '';
        this.form.itemName = '';
        this.form.itemPriceId = '';
        this.form.itemId = '';
      }
    },

    handleReceiveChange(id) {
      if (id) {
        // 根据选中的货物ID查找对应的货物信息
        const selectedGoods = this.receiveCompanyList.find(goods => goods.id === id);
        if (selectedGoods) {
          // 设置货物规格（禁用状态）
          this.form.receiveCompanyId = selectedGoods.id || '';
          this.form.receiveCompany = selectedGoods.name || '';
        }
      } else {
        // 清空选择时，重置相关字段
        this.form.receiveCompanyId = '';
        this.form.receiveCompany =  '';
      }
    },

    handleSendoutChange(id) {
      if (id) {
        // 根据选中的货物ID查找对应的货物信息
        const selectedGoods = this.sendOutCompanyList.find(goods => goods.id === id);
        if (selectedGoods) {
          // 设置货物规格（禁用状态）
          this.form.sendoutCompanyId = selectedGoods.id || '';
          this.form.sendoutCompany = selectedGoods.name || '';
        }
      } else {
        // 清空选择时，重置相关字段
        this.form.sendoutCompanyId = '';
        this.form.sendoutCompany =  '';
      }
    },

    /** 获取商品列表 */
    getGoodsList() {
      // 这里需要替换为实际的API调用
      getGoodsPriceInfoList(this.paramName).then(response => {
        this.goodsList = response.rows
      })
    },
    /** 获取商品列表 */
    getSendOutCompanyList() {
      // 这里需要替换为实际的API调用
      getSendOutCompanyInfoList(this.paramName).then(response => {
        this.sendOutCompanyList = response.rows
      })
    },
    /** 获取商品列表 */
    getReceiveCompanyList() {
      // 这里需要替换为实际的API调用
      getReceiveCompanyInfoList(this.paramName).then(response => {
        this.receiveCompanyList = response.rows
      })
    },
    /** 查询销售计划列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0]
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1]
      }
      listSalePlan(this.queryParams).then(response => {
        this.salePlanList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        tenantId: null,
        updateTime: null,
        createUserId: null,
        createOrgId: null,
        updateUserId: null,
        updateUserName: null,
        isDelete: null,
        orgId: null,
        sqare01: null,
        sqare02: null,
        sqare03: null,
        sqare04: null,
        sqare05: null,
        sqare06: null,
        name: null,
        number: null,
        pickCode: null,
        contractId: null,
        sendoutCompany: null,
        receiveCompany: null,
        signdate: null,
        enddate: null,
        contractNumber: null,
        contractName: null,
        sendoutCompanyId: null,
        receiveCompanyId: null,
        type: null,
        handledby: null,
        planState: null,
        state: null,
        handledbyOrg: null,
        reviewerId: null,
        reviewer: null,
        reviewbyOrg: null,
        reviewTime: null,
        checkState: null,
        createOrgName: null,
        handledbyOrgId: null,
        itemName: null,
        itemPrice: null,
        total: null,
        itemModel: null,
        completed: null,
        remain: null,
        completionRate: null,
        waybillQty: null,
        plancarQty: null,
        planCompletedcarQty: null,
        planRemaincarQty: null,
        createUserName: null,
        createTime: null,
        deductionFlag: null,
        stockId: null,
        contactId: null,
        stockName: null,
        itemId: null,
        itemNumber: null,
        packageNum: null,
        cube: null,
        incrementTotal: null,
        stockIds: null,
        freezeQuantity: null,
        itemPriceId: null,
        itemType: null,
        priceType: null,
        settlementPrice: null,
        settlementAmount: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加销售计划"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getSalePlan(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改销售计划"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSalePlan(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addSalePlan(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除销售计划编号为"' + ids + '"的数据项？').then(function() {
        return delSalePlan(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/salePlan/export', {
        ...this.queryParams
      }, `自定义字段导出_${new Date().getTime()}.xlsx`)
    },
    handleSpecExport() {
      const param = {}
      this.download('/system/salePlan/exportNew', {

      }, `salePlan_${new Date().getTime()}.xlsx`)

    }
  }
}
</script>
